package com.std.getstuffdone;

import models.Utility;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class StartEndTimeEntry extends Activity implements OnClickListener{
	
	// UI buttons for setting and clearing a start time
	Button mSetStartTime;
	Button mSetEndTime;
	Button mSave;
	Button mCancel;
	
	// store the selected start time
	private int mStartHour;
	private int mStartMinute;
	private int mEndHour;
	private int mEndMinute;
	private Time startTime = null;
	private Time endTime = null;
	
	static final int START_TIME_DIALOG_ID = 0;
	static final int END_TIME_DIALOG_ID = 1;
	static final String START_TIME_NOT_SET = "Set start time";
	static final String END_TIME_NOT_SET = "Set end time";
	static final String TIME_NOT_SET = "TIME_NOT_SET";
	static final String TIME_SET_BUT_INVALID = "TIME_SET_BUT_INVALID";
	
	private String startTimeString = START_TIME_NOT_SET;
	private String endTimeString = END_TIME_NOT_SET;
		
	public void onCreate(Bundle savedInstanceState){
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.startendtimeentryactivity);
		setListeners();		
	}

	public void onClick(View v) {
		if(v.getId() == R.id.changeScheduleStartTimeButton){
			showDialog(START_TIME_DIALOG_ID);
		} else if(v.getId() ==  R.id.changeScheduleEndTimeButton){
			showDialog(END_TIME_DIALOG_ID);
		} else if(v.getId() == R.id.saveScheduleTimes) {
			
			String startTimeString = mSetStartTime.getText().toString();
			String endTimeString = mSetEndTime.getText().toString();
			
			if(startTimeString.equalsIgnoreCase(START_TIME_NOT_SET) ||
					endTimeString.equalsIgnoreCase(END_TIME_NOT_SET)) {
				
				// start time or end time not set
				displayAlertDialog(TIME_NOT_SET);
						
			} else if (!isValidTime()) {
				// start time and end time set, but end time is not set to be later than the start time
				displayAlertDialog(TIME_SET_BUT_INVALID);
				
			} else {
				// all input valid
				Bundle bundle = new Bundle();
				bundle.putString(Utility.BUNDLE_TASK_START_TIME, startTimeString);
				bundle.putString(Utility.BUNDLE_TASK_END_TIME, endTimeString);
				
				Intent in = new Intent();
				in.putExtras(bundle);
				setResult(Utility.RETURN_CODE_START_END_TIME_INFO, in);
		    	finish();
			}
		}
		else if(v.getId() == R.id.cancelScheduleTimes) {
			Intent in = new Intent();
			setResult(Utility.RETURN_CODE_CANCEL, in);
	    	finish();
		}
	}
	
	public void setListeners(){
		// get handlers to the buttons
		mSetStartTime = (Button) findViewById(R.id.changeScheduleStartTimeButton);
		mSetEndTime = (Button) findViewById(R.id.changeScheduleEndTimeButton);
		mSave = (Button) findViewById(R.id.saveScheduleTimes);
		mCancel = (Button) findViewById(R.id.cancelScheduleTimes);
		mSetStartTime.setOnClickListener(this);
		mSetEndTime.setOnClickListener(this);
		mSave.setOnClickListener(this);
		mCancel.setOnClickListener(this);
	}
	
	// creates a new pop-up dialog to enter the start time
		@Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case START_TIME_DIALOG_ID:
	            return new TimePickerDialog(this,
	                    mStartTimeSetListener, mStartHour, mStartMinute, false);
	            
	        case END_TIME_DIALOG_ID:
	            return new TimePickerDialog(this,
	                    mEndTimeSetListener, mEndHour, mEndMinute, false);
	            
	        }
		 
	        return null;
	    }
		
		// updates the start time displayed on the mPickTime button
	    private void updateStartTimeDisplay() {
	        mSetStartTime.setText(
	            new StringBuilder()
	                    .append(pad(mStartHour)).append(":")
	                    .append(pad(mStartMinute)));
	        startTimeString = mSetStartTime.getText().toString();
	    }
	    
		// updates the start time displayed on the mPickTime button
	    private void updateEndTimeDisplay() {
	        mSetEndTime.setText(
	            new StringBuilder()
	                    .append(pad(mEndHour)).append(":")
	                    .append(pad(mEndMinute)));
	        endTimeString = mSetEndTime.getText().toString();
	    }
	    
	    // returns true of the end time is set to be later than the start time
	    private boolean isValidTime() {
	    	// get the time string inputs
	    	String startTimeString = mSetStartTime.getText().toString();
			String endTimeString = mSetEndTime.getText().toString();
			String[] startHourMin = startTimeString.split(":");
			String[] endHourMin = endTimeString.split(":");
			
			// convert them to time objects for comparison
			startTime = new Time();
			endTime = new Time();
			startTime.set(0, Integer.parseInt(startHourMin[1]), Integer.parseInt(startHourMin[0]), 0, 0, 0);
			endTime.set(0, Integer.parseInt(endHourMin[1]), Integer.parseInt(endHourMin[0]), 0, 0, 0);
			
			// compare
			int diff = Time.compare(startTime, endTime);
			if(diff != 0){
				return true;
			} else {
				return false;
			}
		}
	   
	   // the callback received when the user "sets" the time in the dialog
	    private TimePickerDialog.OnTimeSetListener mStartTimeSetListener =
	        new TimePickerDialog.OnTimeSetListener() {
	      public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
	                mStartHour = hourOfDay;
	                mStartMinute = minute;
	                updateStartTimeDisplay();
	            }
	      };
	      
	      	// the callback received when the user "sets" the time in the dialog
		    private TimePickerDialog.OnTimeSetListener mEndTimeSetListener =
		        new TimePickerDialog.OnTimeSetListener() {
		      public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
		                mEndHour = hourOfDay;
		                mEndMinute = minute;
		                updateEndTimeDisplay();
		            }
		      };
	      
	      private static String pad(int c) {
	          if (c >= 10)
	              return String.valueOf(c);
	          else
	              return "0" + String.valueOf(c);
	      }
	      
	 	    // displays an alert dialog to user to indicate invalid input
			private void displayAlertDialog(String conflictType) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Invalid Time Input");
				
				// build message depending on conflict type
				if(conflictType.equals(TIME_NOT_SET)){
					builder.setMessage("Both Start Time and End Time must be set");
				} else {
					builder.setMessage("Start and End times cannot be the same");
				}
				
				builder.setInverseBackgroundForced(true);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
}
